#!/usr/bin/python

import os,sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import time
import threading
import re
from  xapi_get_all_host import *
from com.host_option import get_hostinfo
from utils.mode_logger import log
logger = log()
logger.info("----upate starting---------")
         
class ThreadDemo(threading.Thread):
    def __init__(self,host_ip,password):
        threading.Thread.__init__(self)
        self.host_ip=host_ip
        self.password=password
        #self.start()
        
    def run(self):
        update_ga(self.host_ip,self.password)
       
            
    def stop(self):
        self.thread_stop = True
        
def update_ga(host_ip,pwd):
    #from  xapi_vm_param_value import *
    try:
        check_status=check_host_vm_status(host_ip,pwd)
        test=check_status.get_vm_list()
    except Exception,e:
        logger.criticl(e)
    for s in test:
        for i in range(len(s)):
            vm_name=s['name']
            vm_ipaddress=s['ipaddress']
            cpu_used=[]
            global cpu_value
            cpu_value=0    
            sp=vm_ipaddress + ":" + vm_name.lower()
            if s['value'].keys() == None:
                logger.criticl("can't get date from xenserver ,check local time")
                sys.exit()
            for pa in s['value'].keys():
                get_values=s['value'].get(pa)
                gangliaMetric=""
                if str(pa)== 'memory_target':
                    free_mem=0
                    if s['value'].get('memory_internal_free') == None:
                        free_mem=0
                    else:
                        free_mem=s['value'].get('memory_internal_free')
                    get_value=float(get_values)/1024/1024-(float(free_mem)/1024)
                    gangliaMetric = "/usr/bin/gmetric --name='Memmory_Used' --spoof=" + sp + " --value="+str(get_value)+" --type=double --units=MB"
                elif re.search('cpu',str(pa)):
                    cpu_used.append(s['value'].get(pa))
                elif str(pa) == ('vbd_xvda_write'):
                    gangliaMetric = "/usr/bin/gmetric --name=Disk_write --spoof=" + sp + " --value="+str(get_values)+" --type=double --units=seconds"
                elif str(pa) == ('vbd_xvda_read'):
                    gangliaMetric = "/usr/bin/gmetric --name=Disk_read --spoof=" + sp + " --value="+str(get_values)+" --type=float --units=bps"
                elif str(pa) == ('vif_0_tx'):
                    gangliaMetric = "/usr/bin/gmetric --name='network_out_report' --spoof=" + sp + " --value="+str(get_values)+" --type=float --units=bps"
                elif str(pa) == ('vif_0_rx'):
                    gangliaMetric = "/usr/bin/gmetric --name='network_in_report'  --spoof=" + sp + " --value="+str(get_values)+" --type=float --units=bps"
                if gangliaMetric != "":
                        print gangliaMetric
                        os.system(gangliaMetric)
                for v in cpu_used:
                    cpu_value+=float(v)
                    if cpu_value == 0:
                        logger.info("don't get cpu values")
                    else:
                        cpuMetric = "/usr/bin/gmetric --name='AVG_Cpu_Used'" + " --spoof=" + sp + " --value="+str(cpu_value/(len(cpu_used))*100)+" --type=float --units=pecent"
                    #print cpuMetric
                        os.system(cpuMetric)
                    #   print res
            time.sleep(1) 

def main():
    while 1:
        path = os.path.dirname(os.path.abspath(__file__))
        try:
            host_list=get_hostinfo()
        except Exception,e:
            logger.criticl(e)
        s=3
        t=0
        ths_list=[]
        for i in range(len(host_list)):
            sou=host_list[t:s]
            t+=3
            s+=3
            for th in sou:
                host_ip=th['url']
                pwd=os.popen('/usr/bin/java -jar '+path+'/decrypt_password.jar '+th['password']).readlines()
                logger.criticl(pwd)
                ths=ThreadDemo(host_ip,pwd[0])
                #ths.setDaemon(True)
                logger.info(host_ip)
                ths_list.append(ths)
                ths.start()
            for ts in ths_list:
                ts.join()	
            if t > len(host_list):
                break

if __name__ == "__main__":
    main()

